/**   
 * @Title: ActivityTaskQueue.java 
 * @Package cn.edu.cdtu.healthclient.task
 * @Description: TODO 
 * @author 
 * @date 
 * @version V0.0   
 */
package cn.edu.cdtu.healthclient.task;

import java.util.LinkedList;
import java.util.Queue;

/** 
 * @ClassName: ActivityTaskQueue 
 * @Description: Activity的任务执行队列
 * @author 
 * @date 
 *  
 */
public class ActivityTaskQueue extends Thread {
	
	/*
	 * 任务队列启动标识
	 */
	private boolean isRunning = false;
	/*
	 * 队列终止标识
	 */
	private volatile boolean exit = false;
	/*
	 * 任务队列
	 */
	private volatile Queue<Thread> taskList = new LinkedList<Thread>();

	
	/**
	 * 
	 * @Title: addTask 
	 * @Description: 向队列添加任务
	 * @return void
	 * @throws 
	 *
	 * @param task
	 */
	public void addTask(Thread task){
		synchronized (taskList) {
			taskList.offer(task);
			if(isRunning){
				taskList.notifyAll();
			}
		}
	}
	
	/**
	 * @return the isRunning
	 */
	public boolean isRunning() {
		return isRunning;
	}
	/**
	 * 
	 * @Title: shutdownTaskQueue 
	 * @Description: 终止任务队列
	 * @return void
	 * @throws 
	 *
	 */
	public void shutdownTaskQueue(){
		synchronized (taskList) {
			exit = true;
			if(isRunning){
				taskList.notifyAll();
			}
		}
	}
	
	/* (non-Javadoc)
	 * <p>Title: run</p> 
	 * <p>Description: 执行队列中的任务
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		isRunning = true;
		while (!exit) {
			synchronized (taskList) {
				Thread task = null;
				if(taskList.size() < 1){
					try {
						taskList.wait();
						task = taskList.poll();
						if(exit){
							break;
						}
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				if(task == null){
					task = taskList.poll();
				}
				task.start();
			}
		}
	}

	/* (non-Javadoc)
	 * <p>Title: start</p> 
	 * <p>Description: 任务暂停后从新执行任务的方法.  
	 * @see java.lang.Thread#start()
	 */
	@Override
	public synchronized void start() {
		// TODO Auto-generated method stub
		exit = false;
		super.start();
	}

}
